import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/Login.vue'
import Home from '@/components/Home.vue'
import Welcome from '@/components/Welcome.vue'
import Addcp from '@/components/cp/Addcp.vue'
import Listcp from '@/components/cp/Listcp.vue'
import Editcp from '@/components/cp/Editcp.vue'
import Admin from '@/components/user/Admin.vue'
import Dingdan from '@/components/Dingdan.vue'
import Report from '@/components/report/report.vue'
import Gonggao from '@/components/gonggaos/gonggao.vue'

import '@/assets/css/global.css' // 导入全局样式

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    // 地址重定向
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
      path: '/home',
      component: Home,
      redirect: '/welcome',
      children: [
        { path: '/cp/addcp', component: Addcp },
        { path: '/cp/listcp', component: Listcp },
        { path: '/cp/:id/editcp', component: Editcp },
        { path: '/welcome', component: Welcome },
        { path: '/admin', component: Admin },
        { path: '/dingdan', component: Dingdan },
        { path: '/reports', component: Report },
        { path: '/gonggaos', component: Gonggao }
      ]
    }
  ]
})

// 导航守卫
router.beforeEach((to, from, next) => {
  // to代表将要访问的路径，next()表示直接放行 next('/login')强制跳转登录页 from表示从哪个路径跳转而来
  if (to.path === '/login') return next()
  const tokenStr = sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

export default router
